package com.woniumall.web;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniumall.pojo.Category;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @auther linke
 * @create 2021-10-28 16:38
 * 反射对象类
 */
public class BaseServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //获取请求路径
        String requestURI = request.getRequestURI();
        //获取方法名
        String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
        //获取字节码对象
        Class clazz = this.getClass();
        try {
            //获取方法对象
            Method method = clazz.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            //调用方法
            method.invoke(this,request,response);
        } catch (Exception e) {
            e.printStackTrace();
            throw  new RuntimeException("BaseServlet...初始化异常");
    }
    }
    public void responseUtil(HttpServletResponse response,Object obj) throws Exception {
      /*  //设置中文响应格式
        response.setContentType("text/html;charset=utf-8");*/
        //json转换后响应
        ObjectMapper om = new ObjectMapper();
       /* String json = om.writeValueAsString(list);
        response.getWriter().write(json);*/
        //简写
        om.writeValue(response.getWriter(),obj);
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }
}
